<template>
  <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="demo-ruleForm" hide-required-asterisk
           label-width="0"
           status-icon>
    <h3>登录</h3>
    <el-form-item prop="username">
      <el-input v-model.trim="ruleForm.username" :prefix-icon="User" placeholder='请输入用户名' type="text"/>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model.trim="ruleForm.password" :prefix-icon="Lock" maxlength="6" placeholder="请输入密码"
                show-password
                show-word-limit type="text"/>
    </el-form-item>
    <el-form-item class="btn">
      <el-button :icon="Finished" plain round type="primary" @click="submitForm(ruleFormRef)">
        提交
      </el-button>
      <el-button :icon="Refresh" plain round type="primary" @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { rules } from '@/config/formConfig'
import { LoginService } from '@/api'
import { EncryptPassword } from '@/utils/commonUtils'
import { Finished, Lock, Refresh, User } from '@element-plus/icons-vue'
import { Message } from '@/plugins/element'
import { useStaff, useToken } from '@/store'
import { useRouter } from 'vue-router'

const Token = useToken()
const Staff = useStaff()
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({ username: '金秀英', password: '123456' })
const router = useRouter()
// 表单提交并验证
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await LoginService.login(EncryptPassword(ruleForm)).then(async res => {
        console.log(res)
        const { token, tokenHeader } = res
        Token.$patch(state => {
          state.token = token
          state.tokenHeader = tokenHeader
        })
        await router.push({ name: 'home' })
      })
    } else {
      Message.error('请输入正确的内容')
      console.log(fields)
    }
  })
}

// 表单内容重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style lang="scss" scoped>
h3 {
  text-align: center;
  letter-spacing: 30px;
  font-size: 2em;
}

:deep(.btn > .el-form-item__content) {
  justify-content: space-around;
}

.el-form {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  height: 100%;
}
</style>